#include"heap.h"

void HeapInit(Heap* hp)
{
	hp->a = NULL;
	hp->capacity = hp->size = 0;
}

void HeapDestory(Heap* hp)
{
	free(hp->a);
	hp->a = NULL;;
	hp->capacity = hp->size = 0;
}

void Swap(int *x,int* y)
{
	*x = *x ^ *y;
	*y = *x ^ *y;
	*x = *x ^ *y;
}

void AdjustUp(HPDataType* arr,int child)
{
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (arr[child] > arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(Heap* hp, HPDataType x)
{
	assert(hp);
	if (hp->capacity == hp->size)
	{
		int newcapcity = hp->capacity == 0 ? 4 : 2 * hp->capacity;
		HPDataType* arr = (HPDataType*)realloc(hp->a,newcapcity * sizeof(HPDataType));
		if (arr == NULL)
		{
			perror("realloc fail");
			exit(1);
		}
		hp->a = arr;
		hp->capacity = newcapcity;
		hp->a[hp->size] = x;
		AdjustUp(hp->a, hp->size);
	}
}

bool HPEmpty(Heap* php)
{
	assert(php);
	return php->size == 0;
}

void AdjustDown(HPDataType* arr, int parent, int n)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && arr[child] < arr[child + 1])
		{
			child++;
		}
		if (arr[child] > arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else {
			break;
		}
	}
}

void HeapPop(Heap* hp)
{
	assert(!HPEmpty(hp));
	Swap(&hp->a[0], &hp->a[hp->size - 1]);
	--hp->size;
	AdjustDown(hp->a, 0, hp->size);
}

HPDataType HeapTop(Heap* hp)
{
	assert(!HPEmpty(hp));
	return hp->a[0];
}

int HeapSize(Heap* hp)
{
	return hp->size;
}

void HeapSort(int* a, int n)
{
	for (int i = 0; i < n; i++)
	{
		AdjustUp(a, i);
	}
	int end = n - 1;
	while (end > 0)
	{
		Swap(&a[0], &a[end]);
		AdjustDown(a, 0, end);
		end--;
	}
}